package com.alcj.controller;

import com.alcj.common.constant.SysConstant;
import com.alcj.common.utils.CmnUtil;
import com.alcj.common.utils.MultipartFileUtil;
import com.alcj.model.User;
import com.alcj.service.UserService;
import com.alibaba.fastjson.JSONObject;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * @author :hzy
 * @version :v1.0
 * @Package :com.alcj.controller
 * @Description :${TODO}(用户注册登录)
 * @date :2017/9/5 0005 上午 11:10
 */
@Controller
@RequestMapping("/user")
public class LoginController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    UserService userService;

    @RequestMapping("/confirmRegister")
    public String register(@RequestParam("verifyphoto") MultipartFile verifyphoto, HttpServletRequest request, Model model) {

        try {
            String username = (String) request.getParameter("username");
            String userpwd = (String) request.getParameter("password");
            String usertype = (String) request.getParameter("usertype");
            String telphone = (String) request.getParameter("telphone");
            String realname = (String) request.getParameter("realname");
            String idcard = (String) request.getParameter("idcard");
            String companyname = (String) request.getParameter("companyname");
            // 设定注册内容
            User parmInfo = new User();
            // 用户名
            parmInfo.setUsername(username);
                            // 密码
            parmInfo.setUserpwd(userpwd);
            // 手机号
            parmInfo.setTelphone(telphone);
            // 用户类型
            parmInfo.setUsertype(usertype);
            // 联系人姓名
            parmInfo.setRealname(realname);
            // 身份证号
            parmInfo.setIdcardno(idcard);
            // 公司名称
            parmInfo.setCompanyname(companyname);
            if(usertype.equals("1")){
                // 营业执照
                String  uploadName = MultipartFileUtil.uploadFile(verifyphoto);
                parmInfo.setVerifyphoto(uploadName);
            }
            int result = userService.registerUser(parmInfo);

            if (1 == result) {
                model.addAttribute("status", "0");
                model.addAttribute("msg", "注册成功");
            } else {
                model.addAttribute("status", "1");
                model.addAttribute("msg", "注册失败");
            }
        } catch (Exception e) {
            // 异常报错
            logger.error("用户注册异常 : {}", e.getMessage());
            logger.error("异常详细信息 :", e);
            return SysConstant.ERROR_PAGE_500;
        }

        return "registerSuccess";

    }

    @RequestMapping("/login")
    @ResponseBody
    public JSONObject login(HttpServletRequest request, Model model, HttpServletResponse response) {
        // json结果
        JSONObject resultJson = new JSONObject();
        try {
            // 用户名
            String userName = (String) request.getParameter("userName");
            // 密码
            String userPwd = (String) request.getParameter("userPwd");
            // 验证码
            String checkPhoneVerifyCode = (String) request.getParameter("verifyCode");
            // 记住用户名
            String rember = (String) request.getParameter("rember");
            //获取session中的验证码
            String verifyCode = (String) request.getSession().getAttribute("verifyCode");
            //判断验证码是否为空
            if (CmnUtil.isEmpty(checkPhoneVerifyCode) || CmnUtil.isEmpty(verifyCode)) {
                resultJson.put("msg","验证码不正确，请重新输入");
                return resultJson;
            } else {
                if (!checkPhoneVerifyCode.toLowerCase().equals(verifyCode)) {
                    resultJson.put("msg","验证码不正确，请重新输入");
                    return resultJson;
                }
            }
            // 设定用户条件
            User parmInfo = new User();
            parmInfo.setUsername(userName);
            parmInfo.setUserpwd(userPwd);

            // check用户
            String message = userService.checkUserInfo(parmInfo,request.getSession());

            // 用户验证成功
            if (CmnUtil.isEmpty(message)) {
                if("1".equals(rember)){
                    // 记住用户名自动登录
                    String cookUserName = CmnUtil.getCookieUser(request.getCookies());
                    if(CmnUtil.isEmpty(cookUserName) || !cookUserName.equals(userName)){

                        // 把用户名存入到cookie中
                        Cookie cookie = new Cookie("ALCJUser",userName);
                        //设置时间为1年
                        cookie.setMaxAge(365*24*3600);
                        cookie.setPath("/");
                        //把cookie给浏览器
                        response.addCookie(cookie);
                    }
                }
                resultJson.put("userName",userName);
            }
            resultJson.put("msg",message);
        } catch (Exception e) {
            // 异常报错
            logger.error("用户登录异常 : {}", e.getMessage());
            logger.error("异常详细信息 :", e);
            return resultJson;
        }
        return resultJson;
    }

    @RequestMapping("/logout")
    @ResponseBody
    public String logout(HttpServletRequest request, Model model, HttpServletResponse response) {
        try {
            // 清空session中的用户信息
            request.getSession().removeAttribute("User");
            // 作废session
            request.getSession().invalidate();
            return "1";
        } catch (Exception e) {
            // 异常报错
            logger.error("用户登录异常 : {}", e.getMessage());
            logger.error("异常详细信息 :", e);
            return "";
        }
    }

    @RequestMapping("/resetPwd")
    @ResponseBody
    public JSONObject resetPwd(HttpServletRequest request, Model model, HttpServletResponse response) {
        // json结果
        JSONObject resultJson = new JSONObject();
        try {
            // 用户名
            String telphone = (String) request.getParameter("telphone");
            // 密码
            String newPassword = (String) request.getParameter("newPassword");
            // 验证码
            String checkPhoneVerifyCode = (String) request.getParameter("phVerify");
            //获取session中的验证码
            String verifyCode = (String) request.getSession().getAttribute("phoneVerifyCode");
            //判断验证码是否为空
            if (CmnUtil.isEmpty(checkPhoneVerifyCode) || CmnUtil.isEmpty(verifyCode)) {
                resultJson.put("msg","验证码不正确，请重新输入");
                return resultJson;
            } else {
                if (!checkPhoneVerifyCode.toLowerCase().equals(verifyCode)) {
                    resultJson.put("msg","验证码不正确，请重新输入");
                    return resultJson;
                }
            }
            // 设定用户条件
            User parmInfo = new User();
            parmInfo.setTelphone(telphone);
            parmInfo.setUserpwd(newPassword);

            // check用户
            int result = userService.uplPwdByTelphone(parmInfo);
            if(result == 1){
                // 重置密码成功
                resultJson.put("msg","重置密码成功");
            }else {
                // 重置密码失败
                resultJson.put("msg","重置密码失败");
            }
        } catch (Exception e) {
            // 异常报错
            logger.error("重置密码异常 : {}", e.getMessage());
            logger.error("异常详细信息 :", e);
            return resultJson;
        }
        return resultJson;
    }
}
